package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminLoginMapper;
import com.heima.admin.service.AdminLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class AdminLoginServiceImpl extends ServiceImpl<AdminLoginMapper, AdUser> implements AdminLoginService {
    /**
     * 管理员登录
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        log.info("【管理员登录】---begin");
        log.info("【检查参数】:{}", adUserDto);
        //1.检查参数
        if (adUserDto==null || adUserDto.getPassword()==null || adUserDto.getName()==null){ //无效参数
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.校验登录信息
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        if (adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST); //数据不存在
        }

        //3.加密 + salt
        String adPassword = adUser.getPassword();
        String salt = adUser.getSalt();
        String pwd = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + salt).getBytes());
        log.info("【登录输入密码】:{}", pwd);
        log.info("【数据库密码】:{}", adPassword);
        //4.校验密码
        if (!pwd.equals(adPassword)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR); //秘密错误
        }
        log.info("【登录成功】:{}",adUser);
        //5.生成token,返回jwt数据
        Map map =new HashMap();
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        map.put("token",token);
        adUser.setPassword("");
        adUser.setSalt("");
        map.put("user",adUser);
        log.info("【管理员登录】---end");
        return ResponseResult.okResult(map);
    }
}
